package com.group9.handinhand.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import com.group9.handinhand.service.so.UserSO;
/**
 *  A class for base controller.
 *
 */
public abstract class AbstractBaseController {
	
	@Autowired
	/**
	 * Creates an authentication manager.
	 */
	private AuthenticationManager authenticationManager;
	/**
	 * get user method 
	 * @return user if the user has authentication
	 */
    protected UserSO getUser() {
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (authentication != null) {
	    Object principal = authentication.getPrincipal();
	    if (principal instanceof UserSO) {
	    	return (UserSO) principal;
	    }
	}
	return null;
    }
    /**
     * method for getting user an authenticate it.
     * @param user
     * @param request
     */
	protected void authenticateUserAndSetSession(UserSO user, HttpServletRequest request) {
        String username = user.getUsername();
        String password = user.getPassword();
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

        // generate session if one doesn't exist
        request.getSession();

        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authenticatedUser = authenticationManager.authenticate(token);

        SecurityContextHolder.getContext().setAuthentication(authenticatedUser);		
	}

}
